﻿using System;
using System.IO;
using System.Threading;

namespace RfidCompareWin
{
    public class Logger
    {
        private static readonly Logger _instance = new Logger();
        private static readonly object _lockObject = new object();
        private readonly string _logDirectory;

        // 私有构造函数，确保单例模式
        private Logger()
        {
            // 获取或创建日志目录
            _logDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");
            if (!Directory.Exists(_logDirectory))
            {
                Directory.CreateDirectory(_logDirectory);
            }
        }

        // 公开的静态实例属性
        public static Logger Instance => _instance;

        // 记录日志方法
        public void Log(string message, LogLevel level = LogLevel.Info)
        {
            try
            {
                // 获取今天的日志文件路径
                string logFilePath = GetLogFilePath();

                // 使用锁确保线程安全
                lock (_lockObject)
                {
                    // 追加日志内容
                    using (StreamWriter writer = File.AppendText(logFilePath))
                    {
                        string logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] [{level}] {message}";
                        writer.WriteLine(logEntry);
                    }
                }
            }
            catch (Exception ex)
            {
                // 记录日志失败时的处理
                Console.WriteLine($"Failed to write log: {ex.Message}");
            }
        }

        // 获取日志文件路径
        private string GetLogFilePath()
        {
            string date = DateTime.Now.ToString("yyyy-MM-dd");
            return Path.Combine(_logDirectory, $"log_{date}.txt");
        }
    }

    // 日志级别枚举
    public enum LogLevel
    {
        Debug,
        Info,
        Warning,
        Error,
        Fatal
    }
}
